package cat.joronya.supermanager.privateleague;

import java.text.NumberFormat;
import java.util.Locale;

import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.SimpleCursorAdapter;
import android.widget.SimpleCursorAdapter.ViewBinder;
import android.widget.TextView;
import android.widget.Toast;
import cat.joronya.supermanager.R;
import cat.joronya.supermanager.Supermanager;

public class PrivateLeagueActivity extends ListActivity
{
	// pel Log
	private static final String TAG = "supermanager";
	
	/**
     * The columns we are interested in from the database
     */
    private static final String[] PROJECTION = new String[] {
            Supermanager.PrivateLeagueTeam._ID, 			// 0
            Supermanager.PrivateLeagueTeam.NAME, 			// 1
            Supermanager.PrivateLeagueTeam.MANAGER, 		// 2
            Supermanager.PrivateLeagueTeam.CITY, 			// 3
            Supermanager.PrivateLeagueTeam.POINTS, 			// 4
            Supermanager.PrivateLeagueTeam.GENERAL,			// 5
            Supermanager.PrivateLeagueTeam.BROKER, 			// 6
            Supermanager.PrivateLeagueTeam.MODIFIED_DATE 	// 7
    };
    
    // Gesture detection
    private GestureDetector gestureDetector;
    View.OnTouchListener gestureListener;
    
    private String league = "undefined";
    private long id = 0;
    private String jornada = "undefined";
    private int selectedPosition = R.id.jornada;
    private Cursor cursor = null;
    private Cursor daysCursor = null;
    
    private NumberFormat decform = null;
    private NumberFormat intform = null;
    
	/** Called when the activity is first created. */
	@Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.private_league);
        
        // If no data was given in the intent, then use our default content provider.
        Intent intent = getIntent();
        Uri plUri = getIntent().getData();
        if( plUri == null) {
        	plUri = Supermanager.PrivateLeagueTeam.CONTENT_URI;
            intent.setData(Supermanager.PrivateLeagueTeam.CONTENT_URI);
        }
        
        if( decform == null )
        {
        	decform = NumberFormat.getNumberInstance(new Locale("es","ES"));
        	decform.setMinimumFractionDigits(2);
        }
        if( intform == null )
        {
        	intform = NumberFormat.getNumberInstance(new Locale("es","ES"));
        	intform.setGroupingUsed(true);
        }
        
        // inicialitzem el detector de gestures
        gestureDetector = new GestureDetector(new MyGestureDetector());
        gestureListener = new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                if (gestureDetector.onTouchEvent(event)) {
                    return true;
                }
                return false;
            }
        };
        
        // registrem el gesture listener a les vistes del layout
        registerTouchListener();
        
        // guardem id, aixi el tenim quan reordenem el cursor
        id = intent.getLongExtra("cat.joronya.supermanager.privateleague.id",0);

        // recuperem el nom de la lliga i la jornada
        daysCursor = getDaysOfLeague(id);
        if( daysCursor.moveToLast() )
		{
			league = daysCursor.getString(1);
        	jornada = daysCursor.getString(2);
		}
        
        // inicialment mostrem ordenat per points
        showTeamsJornada();
    }
	
	@Override
	protected void onDestroy() 
	{
		daysCursor.close();
		stopManagingCursor(cursor);
		super.onDestroy();
	}

	private void registerTouchListener()
	{
        View listView = findViewById(android.R.id.list);
        listView.setOnTouchListener(gestureListener);
	}
	
	/**
	 * Retorna el cursor amb el llistat de jornades disponibles a l'historic
	 * de la lliga.
	 * @param id
	 * @return
	 */
	private Cursor getDaysOfLeague(long id)
	{
		 // recuperem el nom de la lliga i la jornada
        PrivateLeagueTeamProvider plTeamProvider = new PrivateLeagueTeamProvider();
        Cursor cursor = plTeamProvider.getPrivateLeagueDays(this, id);
        
        return cursor;
	}
	
	/**
	 * Select next day. And call show active classificacion.
	 */
	private void selectNextDay()
	{
		if( daysCursor.moveToNext() )
		{
			league = daysCursor.getString(1);
        	jornada = daysCursor.getString(2);
		
        	switch (selectedPosition) 
        	{
        		case R.id.jornada:
        			showTeamsJornada();
        			break;
        		case R.id.general:
        			showTeamsGeneral();
        			break;
        		case R.id.broker:
        			showTeamsBroker();
        			break;
        	}
        	
        	Toast.makeText(PrivateLeagueActivity.this, 
        			getResources().getString(R.string.private_league_activity_next_day, jornada), 
        			Toast.LENGTH_SHORT).show();
		}
	}

	/**
	 * Select previous day.
	 */
	private void selectPreviousDay()
	{
		if( daysCursor.moveToPrevious() )
		{
			league = daysCursor.getString(1);
        	jornada = daysCursor.getString(2);
		
        	switch (selectedPosition) 
        	{
        		case R.id.jornada:
        			showTeamsJornada();
        			break;
        		case R.id.general:
        			showTeamsGeneral();
        			break;
        		case R.id.broker:
        			showTeamsBroker();
        			break;
        	}
        	
        	Toast.makeText(PrivateLeagueActivity.this, 
        			getResources().getString(R.string.private_league_activity_previous_day, jornada), 
        			Toast.LENGTH_SHORT).show();
		}
	}

	@Override
    public boolean onTouchEvent(MotionEvent event) 
	{
        if (gestureDetector.onTouchEvent(event))
	        return true;
	    else
	    	return false;
    }
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) 
    {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.private_league, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) 
    {
        // Handle item selection
        switch (item.getItemId()) 
        {
        	case R.id.jornada:
        		showTeamsJornada();
        		return true;
        	case R.id.general:
        		showTeamsGeneral();
        		return true;
        	case R.id.broker:
        		showTeamsBroker();
        		return true;
        	default:
        		return super.onOptionsItemSelected(item);
        }
    }
    
	private void showTeamsJornada()
	{
		// marquem la posicio seleccionada
		selectedPosition = R.id.jornada;

		// canviem el titular del header "Lliga: Supervermut - Jornada 29"
        TextView classificationTextView = (TextView) findViewById(R.id.private_league_title);
		classificationTextView.setText(getResources().getString(R.string.private_league_title, 
				league, "Jornada "+jornada));

		// tenim cursor?
		if( cursor != null )
			stopManagingCursor(cursor);

		cursor = getContentResolver().query(getIntent().getData(), PROJECTION, 
       		Supermanager.PrivateLeagueTeam._PRIVATE_LEAGUE_ID+" = ? AND "+
       		Supermanager.PrivateLeagueTeam.DAY+" = ? ", 
       		new String[]{Long.toString(this.id),jornada},
            Supermanager.PrivateLeagueTeam.DEFAULT_SORT_ORDER);
        
		startManagingCursor(cursor);

        // Used to map notes entries from the database to views
        SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, 
        		R.layout.private_league_row, 
        		cursor,
                new String[] { Supermanager.PrivateLeagueTeam.NAME,
        					   Supermanager.PrivateLeagueTeam.MANAGER,
        					   Supermanager.PrivateLeagueTeam.POINTS}, 
        		new int[] { R.id.team,
        					R.id.manager,
        					R.id.points});
        
        adapter.setViewBinder(new ViewBinder()
        {
        	public boolean setViewValue(View aView, Cursor aCursor, int aColumnIndex)
        	{
        		if( aColumnIndex == 4 )
        		{
        			float points = aCursor.getFloat(aColumnIndex);
        			TextView textView = (TextView) aView;
        			textView.setText(decform.format(points));
        			return true;
        		}
        		else
        		{
        			return false;
        		}
        	}
        });

        setListAdapter(adapter);
	}
	
	private void showTeamsGeneral()
	{
		// marquem la posicio seleccionada
		selectedPosition = R.id.general;

		// canviem el titular del header "Lliga: Supervermut - General"
        TextView classificationTextView = (TextView) findViewById(R.id.private_league_title);
		classificationTextView.setText(getResources().getString(R.string.private_league_title, 
				league, "General"));
		
		if( cursor != null )
			stopManagingCursor(cursor);
		
		cursor = getContentResolver().query(getIntent().getData(), PROJECTION, 
				Supermanager.PrivateLeagueTeam._PRIVATE_LEAGUE_ID+" = ? AND "+
	       		Supermanager.PrivateLeagueTeam.DAY+" = ? ", 
	       		new String[]{Long.toString(this.id),jornada},
            Supermanager.PrivateLeagueTeam.GENERAL_SORT_ORDER);
        
		startManagingCursor(cursor);
		
		// Used to map notes entries from the database to views
        SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, 
        		R.layout.private_league_row, 
        		cursor,
                new String[] { Supermanager.PrivateLeagueTeam.NAME,
        					   Supermanager.PrivateLeagueTeam.MANAGER,
        					   Supermanager.PrivateLeagueTeam.GENERAL}, 
        		new int[] { R.id.team,
        					R.id.manager,
        					R.id.points});
        
        adapter.setViewBinder(new ViewBinder()
        {
        	public boolean setViewValue(View aView, Cursor aCursor, int aColumnIndex)
        	{
        		if( aColumnIndex == 5 )
        		{
        			float general = aCursor.getFloat(aColumnIndex);
        			TextView textView = (TextView) aView;
        			textView.setText(decform.format(general));
        			return true;
        		}
        		else
        		{
        			return false;
        		}
        	}
        });
        
        setListAdapter(adapter);
	}
	
	private void showTeamsBroker()
	{
		// marquem la posicio seleccionada
		selectedPosition = R.id.broker;

        // canviem el titular del header "Lliga: Supervermut - BrokerBasket"
		TextView classificationTextView = (TextView) findViewById(R.id.private_league_title);
		classificationTextView.setText(getResources().getString(R.string.private_league_title, 
				league, "BrokerBasket"));

		if( cursor != null )
			stopManagingCursor(cursor);
		
		cursor = getContentResolver().query(getIntent().getData(), PROJECTION, 
				Supermanager.PrivateLeagueTeam._PRIVATE_LEAGUE_ID+" = ? AND "+
	       		Supermanager.PrivateLeagueTeam.DAY+" = ? ", 
	       		new String[]{Long.toString(this.id),jornada},
            Supermanager.PrivateLeagueTeam.BROKER_SORT_ORDER);
        
		startManagingCursor(cursor);
		
		// Used to map notes entries from the database to views
        SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, 
        		R.layout.private_league_row, 
        		cursor,
                new String[] { Supermanager.PrivateLeagueTeam.NAME,
        					   Supermanager.PrivateLeagueTeam.MANAGER,
        					   Supermanager.PrivateLeagueTeam.BROKER}, 
        		new int[] { R.id.team,
        					R.id.manager,
        					R.id.points});
        
        adapter.setViewBinder(new ViewBinder()
        {
        	public boolean setViewValue(View aView, Cursor aCursor, int aColumnIndex)
        	{
        		if( aColumnIndex == 6 )
        		{
        			int broker = aCursor.getInt(aColumnIndex);
        			TextView textView = (TextView) aView;
        			textView.setText(intform.format(broker));
        			return true;
        		}
        		else
        		{
        			return false;
        		}
        	}
        });
        
        setListAdapter(adapter);
	}
	
	/**
	 * Gesture listener to tap left/right and move next/previous day results.
	 * @author pol
	 */
	class MyGestureDetector extends SimpleOnGestureListener 
	{
		private static final int SWIPE_MIN_DISTANCE = 120;
	    private static final int SWIPE_MAX_OFF_PATH = 250;
	    private static final int SWIPE_THRESHOLD_VELOCITY = 200;
	    
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) 
        {
            try 
            {
                if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
                    return false;
                
                // right to left swipe
                if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) 
                {
                    Log.d(TAG,"Left Swipe - nextDay");
                	selectNextDay();
                }
                else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) 
                {
                    Log.d(TAG,"Right Swipe - previousDay");
                    selectPreviousDay();
                }
                else
                {
                    Log.d(TAG,"else Swipe - no change");
                }
            } 
            catch (Exception e)
            {
                // nothing
            }
            return false;
        }

    }
}
